// API基础URL
const API_BASE_URL = 'http://localhost:8080/api/auth';

// 显示消息
function showMessage(message, isSuccess = true) {
    const messageContainer = document.getElementById('errorMessage');
    if (!messageContainer) return;

    messageContainer.innerHTML = message;
    messageContainer.style.display = 'block';
    messageContainer.style.background = isSuccess ? '#d4edda' : '#f8d7da';
    messageContainer.style.color = isSuccess ? '#155724' : '#721c24';

    // 5秒后自动消失
    setTimeout(() => {
        messageContainer.style.display = 'none';
    }, 5000);
}

// 用户注册
function setupRegisterForm() {
    const registerForm = document.getElementById('registerForm');
    if (!registerForm) return;

    registerForm.addEventListener('submit', async (e) => {
        e.preventDefault();

        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;
        const confirmPassword = document.getElementById('confirmPassword').value;

        if (password !== confirmPassword) {
            showMessage('两次输入的密码不一致', false);
            return;
        }

        try {
            const response = await fetch(`${API_BASE_URL}/register`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username, password })
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.message || '注册失败');
            }

            const user = await response.json();
            showMessage(`用户 ${user.username} 注册成功`, true);

            // 注册成功后自动跳转到登录页面
            setTimeout(() => {
                window.location.href = 'login.html?registerSuccess=true';
            }, 1500);
        } catch (error) {
            console.error('注册失败:', error);
            showMessage('注册失败: ' + error.message, false);
        }
    });
}

// 用户登录
function setupLoginForm() {
    const loginForm = document.getElementById('loginForm');
    if (!loginForm) return;

    loginForm.addEventListener('submit', async (e) => {
        e.preventDefault();

        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;

        try {
            const response = await fetch(`${API_BASE_URL}/login`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username, password })
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.message || '登录失败');
            }

            const user = await response.json();

            // 保存用户信息到localStorage
            localStorage.setItem('user', JSON.stringify(user));

            // 跳转到主应用页面
            window.location.href = 'index.html';
        } catch (error) {
            console.error('登录失败:', error);
            showMessage('登录失败: ' + error.message, false);
        }
    });
}

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', () => {
    // 检查URL参数
    const urlParams = new URLSearchParams(window.location.search);

    // 注册成功提示
    if (urlParams.get('registerSuccess') === 'true') {
        showMessage('注册成功，请登录', true);
    }

    // 错误提示
    if (urlParams.get('error') === 'true') {
        showMessage('用户名或密码错误', false);
    }

    // 设置表单事件
    setupRegisterForm();
    setupLoginForm();
});